//
//  AdvertisingListView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/3.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AdvertisingListView: BaseView, UITableViewDelegate, UITableViewDataSource {
    var viewModel:AdvertListViewModel?
    var ongoBtn:UIButton?
    var carriageBtn:UIButton?
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var lastTableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var headView: UIView = {
        let view = UIView()
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }()
    
    lazy var selectLine: UIView = {
        let view = UIView()
        view.backgroundColor = kThemeColor
        return view
    }()
   
    override func setUpUI() -> Void {
        viewModel = dataSource as? AdvertListViewModel
        //注册监听
        viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(changeStates), name: NSNotification.Name.Exchange.adverDidChange, object: nil)
        
        self.addSubview(headView)
        headView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(34)
        }
        
        let line = UIView()
        line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
        headView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        for i in 0..<2 {
            let btn = UIButton()
            btn.tag = BtnTag+i
            btn.setTitleColor(i==0 ? kThemeColor : kTextColor, for: UIControlState.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            btn.addTarget(self, action: #selector(entrustAction(sender:)), for: UIControlEvents.touchUpInside)
            btn.setTitle(KAdvertistArr[i], for: UIControlState.normal)
            headView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.top.bottom.equalToSuperview()
                make.left.equalToSuperview().offset(CGFloat(i)*kSCREEN_WIDTH/2)
                make.width.equalTo(kSCREEN_WIDTH/2)
            }
            if i == 0 {
                headView.addSubview(selectLine)
                selectLine.snp.makeConstraints { (make) in
                    make.width.equalTo(20)
                    make.height.equalTo(2)
                    make.bottom.equalToSuperview().offset(-2)
                    make.left.equalTo(kSCREEN_WIDTH/4-10)
                }
                ongoBtn = btn
            }else {
                carriageBtn = btn
            }
        }
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.mj_header = EoeRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
        tableView.mj_footer = EoeRefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clear
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(34)
        }
        
        self.addSubview(lastTableView)
        lastTableView.isHidden = true
        lastTableView.separatorStyle = UITableViewCellSeparatorStyle.none
        lastTableView.mj_header = EoeRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
        lastTableView.mj_footer = EoeRefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
        lastTableView.delegate = self
        lastTableView.dataSource = self
        lastTableView.backgroundColor = UIColor.clear
        lastTableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(34)
        }
        tableView.creatEmptyView()
        lastTableView.creatEmptyView()
    }
    
   
    
    //MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView.isEqual(self.tableView) {
        return (viewModel?.dateArr.count)!
        }else {
            return (viewModel?.undercarriageArr.count)!
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identy = "identyCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? AdvertisingListCell
        if cell == nil {
            cell = AdvertisingListCell(style: .default, reuseIdentifier: identy)
            cell?.selectionStyle = .none
        }
        cell?.index = indexPath.section
        cell?.delegate = self
        if tableView.isEqual(self.tableView) {
         let model = viewModel?.dateArr[indexPath.section]
         cell?.setModel(model:model!)
         cell?.undercarriageBtn.setTitle(kText("下架"), for: UIControlState.normal)
        }else {
            let model = viewModel?.undercarriageArr[indexPath.section]
            cell?.setModel(model:model!)
            cell?.undercarriageBtn.setTitle(kText("上架"), for: UIControlState.normal)
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let controller = AppealViewController()
//        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 50))
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        let statesLabel = UILabel()
        statesLabel.font = UIFont.systemFont(ofSize: 15)
        statesLabel.textColor = kThemeColor
        view.addSubview(statesLabel)
        statesLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
        }
        
        let model:AdvertInforModel?
        if tableView.isEqual(self.tableView) {
            model  = (viewModel?.dateArr[section])
            statesLabel.text = kText("已上架")
        }else {
            model  = (viewModel?.undercarriageArr[section])
            statesLabel.text = kText("已下架")
            statesLabel.textColor = kTextColor
        }
        let quantityLabel = BaseLabel(style: .oneStyle)
        quantityLabel.font = UIFont.systemFont(ofSize: 15)
        var moneyType  =   model?.moneyType ?? ""
        if AppCacheInfo.default.isEnlish {
            moneyType = " " + moneyType
        }
        quantityLabel.text = String(format: "%@ %d", model?.type == 0 ? (kText("购买") + "\(moneyType)") : (kText("出售") + "\(moneyType)"), model?.id != nil ? (model?.id)! : "")
        view.addSubview(quantityLabel)
        quantityLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        
        let line = UIView()
        line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
        view.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(0.5)
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 10))
        view.themeBackground = ThemeManager.ThemeColorKeys.background3

        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            if (viewModel?.refreshBool)! {
            if (self.viewModel?.refreshAll)! {
                tableView.reloadData()
                lastTableView.reloadData()
            }else {
                if viewModel?.states == 1 {
                    tableView.reloadData()
                }else {
                   lastTableView.reloadData()
                }
            }
          }
    //            if viewModel.isNoMoreData{
    //                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
    //            }else {
    //            }
            self.endRefresh()
            
            
        }
        
    }
    
    @objc func changeStates() {
        if viewModel?.selectIndex == 0 {
            viewModel?.underPage = 1
            viewModel?.archiveInfromation(statesBool: 1, semaphore: nil)
        }else {
            viewModel?.underPage = 1
            viewModel?.archiveInfromation(statesBool: 0, semaphore: nil)
        }
        
    }

    func endRefresh() {
        if (viewModel?.refreshAll)! {
            self.endRefresh(table: tableView)
            self.endRefresh(table: lastTableView)
        }else {
            if viewModel?.states == 1 {
                self.endRefresh(table: tableView)
            }else {
                self.endRefresh(table: lastTableView)
            }
        }
        
    }
    func endRefresh(table:UITableView) {
        table.mj_footer?.endRefreshing()
        table.mj_header?.endRefreshing()
        if table.isEqual(self.tableView) {
        if (viewModel?.dateArr.count)! % 10 != 0{
            table.mj_footer?.endRefreshingWithNoMoreData()
        }else {
            table.mj_footer?.endRefreshing()
        }
            table.mj_footer?.isHidden = viewModel?.dateArr.count != 0 ? false : true
        }else {
            if (viewModel?.undercarriageArr.count)! % 10 != 0{
                table.mj_footer?.endRefreshingWithNoMoreData()
            }else {
                table.mj_footer?.endRefreshing()
            }
            table.mj_footer?.isHidden = viewModel?.undercarriageArr.count != 0 ? false : true
        }
    }
    
    @objc func entrustAction(sender:UIButton) {
        let currentBtn = self.viewWithTag(BtnTag)
        let historyBtn = self.viewWithTag(BtnTag+1)
        if sender.tag == BtnTag {
            selectLine.snp.updateConstraints { (make) in
                make.left.equalToSuperview().offset((currentBtn?.centerX)!-10)
            }
            ongoBtn?.setTitleColor(kThemeColor, for: UIControlState.normal)
            carriageBtn?.setTitleColor(kTextColor, for: UIControlState.normal)
            tableView.isHidden = false
            lastTableView.isHidden = true
            viewModel?.selectIndex = 0
        }else {
            selectLine.snp.updateConstraints { (make) in
                make.left.equalToSuperview().offset((historyBtn?.centerX)!-10)
            }
            carriageBtn?.setTitleColor(kThemeColor, for: UIControlState.normal)
            ongoBtn?.setTitleColor(kTextColor, for: UIControlState.normal)
            tableView.isHidden = true
            lastTableView.isHidden = false
            viewModel?.selectIndex = 1
        }
        
    }
    
    @objc func loadData(compant:UIView) {
        
        if compant.isEqual(tableView.mj_header) {
            viewModel?.page = 1
            viewModel?.archiveInfromation(statesBool: 1, semaphore: nil)
            
        }else if compant.isEqual(tableView.mj_footer){
            viewModel?.page = (viewModel?.page)! + 1
            viewModel?.archiveInfromation(statesBool: 1, semaphore: nil)
            
        }else if compant.isEqual(lastTableView.mj_header) {
            viewModel?.underPage = 1
            viewModel?.archiveInfromation(statesBool: 0, semaphore: nil)
        }else if compant.isEqual(lastTableView.mj_footer) {
            viewModel?.underPage = (viewModel?.underPage)! + 1
            viewModel?.archiveInfromation(statesBool: 0, semaphore: nil)
        }
        
    }
    deinit {
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.Exchange.adverDidChange, object: nil)
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

extension AdvertisingListView:AdvertListDelegate {
    func changeOrderStates(index: Int) {
        if viewModel?.selectIndex == 0 {
            viewModel?.changeAdvertStates(index: index)
        }else {
            viewModel?.changeAdvertStates(index: index)
        }
    }
    
    func editOrder(index: Int) {
        if viewModel?.selectIndex == 0 {
            let model = viewModel?.dateArr[index]
            let controller = AdvertViewController()
            controller.viewModel?.isBuyBool = model?.type == 0 ? true : false
            controller.viewModel?.inforId = model?.id
            controller.viewModel?.isChange = true
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }else {
            let model = viewModel?.undercarriageArr[index]
            let controller = AdvertViewController()
            controller.viewModel?.isBuyBool = model?.type == 0 ? true : false
            controller.viewModel?.inforId = model?.id
            controller.viewModel?.isChange = true
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    
}
